

import 'dart:io';
import 'dart:isolate';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:ip_check_demo/utils/hint_uitl.dart';

/// 单个ip占用进度item
class MyGridItem extends StatefulWidget{

  MaterialColor colors;
  String ipStr;

  MyGridItem(this.colors,this.ipStr);

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _GridItem(colors,ipStr);
  }
}

class _GridItem extends State<MyGridItem>{

  MaterialColor colors = Colors.grey;
  String ipStr;
  bool isConnect = false;

  _GridItem(this.colors,this.ipStr){}

  @override
  void initState() {
    super.initState();
    getColor(ipStr);
  }

  void getColor(String ipStr) async {

    print("正在连接...");
    //同一线程的方式检测ip，容易造成UI卡顿
    // isConnect = await checkConnection(ipStr);
    //使用ISOlate 异步线程的方式
    isConnect = await computeFunc();

    if(isConnect){
      colors = Colors.green;
      print("连接成功");
    }else{
      colors =  Colors.grey;
      print("无法连接");
    }
    if(mounted){
      setState(() {
      });
    }
  }

  Future<bool> computeFunc() async {
    ReceivePort port = ReceivePort();
    Isolate iso = await Isolate.spawn(checkConn,[port.sendPort,ipStr]);
    bool isConn = await port.first as bool;

    port.close();
    iso.kill();
    return isConn;
  }



  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      width: 100,
      height: 30,
      color:colors,
      child: Text(
        ipStr,
        style: const TextStyle(color: Colors.white,
            shadows: [
              Shadow(color: Colors.black, offset: Offset(.5, .5), blurRadius: 2)
            ]),
      ),
    );
  }

  Future<bool> checkConnection(String ip) async {
    try {
      final result = await InternetAddress.lookup(ip);
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        final response = await Process.run('ping', ['-c', '1', '-W', '5', ip]);
        if (response.exitCode == 0) {
          return true;
        }
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  static Future<void> checkConn(List<dynamic> args) async {
    SendPort resultPort = args[0];
    bool isConnect = false;

    final ip = args[1];
    print(ip);
    try {
      final result = await InternetAddress.lookup(ip);
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {

        // final response = await Process.run('ping', ['-c', '1', '-W', '5', ip]);
        final response ;

        if (Platform.isWindows) {
          response = await Process.run('ping', ['/n', '1', '/w', '5000', ip]);
        } else {
          response =  await Process.run('ping', ['-c', '1', '-W', '5', ip]);
        }

        if (response.exitCode == 0) {
          isConnect =  true;

          print('isConnect $isConnect');
          Isolate.exit(resultPort,isConnect);
        }
      }
      print('result 出错$result');
      isConnect =  false;
      Isolate.exit(resultPort,isConnect);
    } catch (e) {
      print('异常');
      isConnect =  false;
      Isolate.exit(resultPort,isConnect);
    }

  }


}

